package com.xiaodou.mjf.web.console.core.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.xiaodou.mjf.application.core.manager.FinancingManager;
import com.xiaodou.mjf.application.core.repository.mybatis.LoanMapper;
import com.xiaodou.mjf.application.core.service.FinancialPackageService;
import com.xiaodou.mjf.application.core.service.FinancingLoanService;
import com.xiaodou.mjf.application.core.service.FinancingService;
import com.xiaodou.mjf.application.core.service.FinancingStatisticsService;
import com.xiaodou.mjf.application.core.service.LoanService;
import com.xiaodou.mjf.entity.core.FinancialPackage;
import com.xiaodou.mjf.entity.core.Financing;
import com.xiaodou.mjf.entity.core.FinancingLoan;
import com.xiaodou.mjf.entity.core.Loan;
import com.xiaodou.mjf.infrastructure.common.components.Result;
import com.xiaodou.mjf.infrastructure.common.controller.ApplicationController;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;

@Controller
@RequestMapping("financing/xiaodou")
public class XiaoDouProductController extends ApplicationController {

	@Resource
	FinancingService financingService;
	@Resource
	FinancingStatisticsService financingStatisticsService;
	@Resource
	LoanService loanService;
	@Resource
	FinancialPackageService financialPackageService;
	@Resource
	FinancingManager financingManager;
	@Resource
	FinancingLoanService financingLoanService;
	@Resource
	LoanMapper loanMapper;

	@RequestMapping("")
	public String list(Financing financing, Model model) {

		return "core/finance/xiaodou/list";
	}

	@RequestMapping(value = { "data.json" })
	@ResponseBody
	public Map<String, Object> data(Financing financing) {
		financing.setType(Financing.TYPE_XIAODOU);
		Page<Financing> page = financingService.pageAll(financing);
		logger.debug("demo: data.json");
		return page(page);
	}

	/**
	 * 获取分页数据
	 * 
	 * @param loan
	 * @return
	 */
	@RequestMapping(value = { "loanData.json" })
	@ResponseBody
	public Map<String, Object> loanData(Loan loan) {
		try {

			List<Loan> entity = Lists.newArrayList();
			Integer term = loan.getTerm() == null ? 3 : loan.getTerm();
			if (loan.getStart() == 1) {
				loan.setStart(0);
			} else {
				loan.setStart(loan.getStart() - 1);
			}
			entity = loanMapper.getLoanListByTerm(loan);
			Integer count = loanMapper.getLoanCountByTerm(term);
			logger.debug("demo: loanData.json");
			return page(count, entity);

		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}
	}

	/**
	 * 产品添加
	 * 
	 * @param financing
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "form", "form/{id}" }, method = RequestMethod.GET)
	public String form(Financing financing, Model model) {
		try {
			List<FinancialPackage> financialPackage = financialPackageService.list();
			model.addAttribute("lists", financialPackage);

		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}
		return "core/finance/xiaodou/form";
	}

	/**
	 * 获取利率值
	 * 
	 * @param term
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "rate", "rate/{term}" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getRate(@PathVariable Integer term, Model model) {
		FinancialPackage financialPackage = financialPackageService.getRate(term);

		Map<String, Object> map = map(true);
		map.put("rate", financialPackage.getInterestRate());
		map.put("minAmount", financialPackage.getMinAmount());
		return map;
	}

	/**
	 * 保存
	 * 
	 * @param financing
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "save" }, method = RequestMethod.POST)
	public String save(Financing financing, Model model) throws Exception {

		try {

			Result result = financingManager.xiaodouSave(financing);

			if (!result.isSuccess()) {
				return result.getMessage();
			}

		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}

		return "redirect:";
	}

	/**
	 * 产品修改
	 */
	@RequestMapping(value = { "update", "update/{id}" }, method = RequestMethod.GET)
	public String update(@PathVariable String id, Model model) {
		try {
			String loanIds = "";
			Financing financing = financingService.get(id);
			List<FinancingLoan> financingLoan = financingLoanService.findByFinancingId(id);
			List<FinancialPackage> financialPackage = financialPackageService.list();
			model.addAttribute("lists", financialPackage);
			model.addAttribute("financing", financing);
			if (financingLoan.size() > 0) {
				for (FinancingLoan source : financingLoan) {
					loanIds += source.getLoanId() + ",";
				}

			}
			model.addAttribute("loanIds", loanIds);

		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}
		return "core/finance/xiaodou/update";
	}

	/**
	 * 产品删除
	 * 
	 * @param id
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "delete", "delete/{id}" })
	@ResponseBody
	public Map<String, Object> delete(@PathVariable String id, Model model) throws Exception {
		Result result = new Result();
		String loanIds = "";
		try {
			// 获取产品信息
			Financing financing = financingService.get(id);
			// 获取贷款信息
			List<FinancingLoan> financingLoan = financingLoanService.findByFinancingId(id);
			if (financingLoan.size() > 0) {
				for (FinancingLoan source : financingLoan) {
					loanIds += source.getLoanId() + ",";
				}

			}
			if (financing != null) {
				financing.setLoanIds(loanIds);
				result = financingManager.meiliDelete(financing);

			}
		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}
		return map(result.isSuccess());
	}

	/**
	 * 产品下架
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "prodDown", "prodDown/{id}" })
	@ResponseBody
	public Map<String, Object> prodDown(@PathVariable String id, Model model) {
		Result result = new Result();
		Financing financing = financingService.get(id);
		if (financing == null) {
			result.setSuccess(false);
			result.setMessage("操作提示：数据不存在");
			return map(result);
		}
		Date currDate = DateUtils.getCurrentTime();
		Date endDate = financing.getEndTime();
		if (DateUtils.compare(currDate, endDate) == 1) {
			result.setSuccess(false);
			result.setMessage("操作提示：产品已过期");
			return map(result);
		}
		financing.setStatus(financing.getStatus() == Financing.INVEST_STATUS_SALE ? Financing.INVEST_STATUS_DOWN : financing.getStatus() == Financing.INVEST_STATUS_DOWN ? Financing.INVEST_STATUS_SALE : financing.getStatus());
		financingService.save(financing);
		result.setSuccess(true);
		result.setMessage("操作提示：执行成功");
		return map(result);
	}

}
